<?php
namespace bc\controller;

use bc\util\Util;
use yii\web\Session;
use bc\model\wx\User;
use bc\wx\Auth;
use bc\model\wx\JsApiModel;
use bc\model\wx\oauth\error\LogModel;
use bc\wx\OAuth;
use bc\model\shop\ShopUserModel;

class FrontController extends BaseController
{
	public $layout = 'default';
	private $_session = null;
	
	
	public function init() {
    	$this->getView()->title = '';
	}
	
	
	/**
	 * 
	 * @param string $scpoe OAuth::SNSAPI_USERINFO | OAuth::SNSAPI_BASE
	 */
	public function setOAuth($scope = OAuth::SNSAPI_USERINFO)
	{
		$code = $this->get('code');
		$appid = $this->wechat()->appid;
		$secret = $this->wechat()->secret;
		
		if(!$code)
		{
			$oauth = new OAuth();
			$oauth->authorize($this->getFullUrl(), $scope);
		}
		
		
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
		$rs = Util::httpGet($url);
		$arr = json_decode($rs, true);
		if($arr['access_token'])
		{
			if($arr['scope'] == 'snsapi_userinfo')
			{
				$userModel = new User();
				$user = $userModel->getRow(['openid' => $arr['openid']]);
				if(!$user)
				{
					//将用户信息写到数据表里
					$accessToken = $arr['access_token'];
					$openid = $arr['openid'];
					$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken}&openid={$openid}&lang=zh_CN";
					$result = Util::httpGet($url);
					$userInfo = json_decode($result, true);
				
					
					$userData['subscribe'] = $userInfo['subscribe']?$userInfo['subscribe']:1;
					$userData['openid'] = $userInfo['openid'];
					$userData['nickname'] = $userInfo['nickname'];
					$userData['language'] = $userInfo['language'];
					$userData['city'] = $userInfo['city']?$userInfo['city']:'';
					$userData['province'] = $userInfo['province']?$userInfo['province']:'';
					$userData['country'] = $userInfo['country']?$userInfo['country']:'';
					$userData['headimgurl'] = $userInfo['headimgurl']?$userInfo['headimgurl']:'';
					$userData['unionid'] = $userInfo['unionid']?$userInfo['unionid']:'';
					$userData['sex'] = $userInfo['sex']?$userInfo['sex']:0;
					$userData['create_time'] = time();
					$userData['type'] = 1;
					$userPid = $userModel->add($userData);
					$user = $userModel->getRowById($userPid);
				
				}
			}
			else 
			{
				$user['openid'] = $arr['openid'];
			}
			
			
			//将用户信息写入session中
			if($user)
			{
				$session = new Session();
				$session->set('user', $user);
				
				$ShopUserModel = new ShopUserModel();
				$ShopUserModel->autoId = 'user_id';
				$shopUser = $ShopUserModel->getRow(['wxid' => $user['openid']]);
				if(!$shopUser)
				{
					//在ecs_users表中创建用户
					$user_data['wxid'] = $user['openid'];
					$user_data['subscribe'] = 2;
					$user_data['wxch_bd'] = 'no';
					$user_data['password_tianxin'] = $this->randomkeys();
					$user_data['reg_time'] = time();
					$ecs_user_id = $ShopUserModel->add($user_data);
					$shopUser = $ShopUserModel->getRowById($ecs_user_id);
					$ShopUserInserModel = new ShopUserModel();
					$ShopUserInserModel->modify(['user_name' => 'wx_' . $ecs_user_id], $ecs_user_id);
					
				}
				$session->set('shop_user', $shopUser);
				
			}
		}
		else 
		{
			$errorData['code'] = $rs;
			$errorData['create_time'] = date('Y-m-d H:i:s');
			$logModel = new LogModel();
			$logModel->add($errorData);
		}
	}
	
	
	
	/**
	 * 配置js sdk
	 * 
	 *	@return array
	 */
	public function configJsApi()
	{

		$auth = new Auth($this->wechat()->appid, $this->wechat()->secret);
		$accessToken = $auth->accessToken;
		
		$jsApiModel = new JsApiModel();
		$ticket = $jsApiModel->getTicket($accessToken);
		
		$baseUrl = $this->getRequest()->getHostInfo().$this->getRequest()->getUrl();
		
		$time = time();
		
		$noncestr = $this->createNonceStr();
		
		$str  = 'jsapi_ticket='.$ticket;
		$str .= '&noncestr='.$noncestr;
		$str .= '&timestamp='.$time;
		$str .= '&url='.$baseUrl;
		
		
		$signature = sha1($str);
		
		$arr['appId'] = $this->wechat()->appid;
		$arr['timestamp'] = $time;
		$arr['noncestr'] = $noncestr;
		$arr['signature'] = $signature;
		$arr['base_url'] = $baseUrl;
		return $arr;
	}
	
	protected function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}
	
	
	protected function randomkeys()
	{
		$pattern='1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
		for($i=0;$i<6;$i++)
		{
			$key .= $pattern{mt_rand(0,35)};    //生成php随机数
		}
		
		return  'pinyou' . $key;
	}
	
}
